package star.cloud.asme.system.operation;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import star.cloud.asme.base.dto.Result;
import star.cloud.asme.base.mybatis.IBaseServiceImpl;
import star.cloud.asme.base.security.SpringSecurityUtil;
import star.cloud.asme.base.utils.ObjectsUtil;
import star.cloud.asme.system.user.UserService;

@Service
@RequiredArgsConstructor
@Slf4j
public class OperationServiceImpl extends IBaseServiceImpl<OperationMapper, Operation> implements OperationService {

    private final OperationMapper operationMapper;

    private final UserService userService;

    @Override
    public Result<Operation> saveEntity(HttpServletRequest request) {
        Operation operation = Operation.builder()//
                .requestUri(request.getRequestURI())//
                .scheme(request.getScheme())//
                .serverPort(request.getServerPort())//
                .serverName(request.getServerName())//
                .remoteHost(request.getRemoteHost())//
                .remoteAddr(request.getRemoteAddr())//
                .method(request.getMethod())//
                .username(SpringSecurityUtil.getUsername())//
                .build();
        Long currentUserId = userService.getOneByCondition("username", operation.getUsername()).getBody().getId();
        operation.setCreatorId(currentUserId);
        operation.setUpdaterId(currentUserId);
        operationMapper.insert(operation);
        return Result.ok(operation);
    }

    @Override
    public Result<IPage<Operation>> getListByConditionsWithPage(Operation operation) {
        IPage<Operation> ipage = new Page<>(operation.getCurrentPage(), operation.getPageSize());
        LambdaQueryWrapper<Operation> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ObjectsUtil.noNullAndEmpty(operation.getMethod()), Operation::getMethod, operation.getMethod());
        lambdaQueryWrapper.like(ObjectsUtil.noNullAndEmpty(operation.getUsername()), Operation::getUsername, operation.getUsername());
        operationMapper.selectPage(ipage, lambdaQueryWrapper);
        setCreatorAndUpdater(ipage);
        return Result.ok(ipage);
    }
}